package com.dtz.order.lb.impl;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.validation.constraints.NotNull;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import com.dtz.order.lb.LoadBalancer;

@Component
public class MyLoadBalancer implements LoadBalancer {
	
	private AtomicInteger atomicInteger = new AtomicInteger(0);
	
	private final int getAndIncrese() {
		int current;
		int next;
		// 自旋锁
		for(;;) {
			current = this.atomicInteger.get();
			next = current >= Integer.MAX_VALUE ? 0 : current + 1;
			if (atomicInteger.compareAndSet(current, next))
                return next;
		}
	}

	@Override
	public ServiceInstance instance(@NotNull List<ServiceInstance> instans) 
	{
		int index = getAndIncrese() % instans.size();
		return instans.get(index);
	}

}
